<?php
/**
 * 功能描述：	表字段管理
 * @datetime	2022-07-11
 * @version   	v2.3.0
 * @author   	ZHL
 * @copyrigh  	2022 ZHL 版权所有
 */

class Admin_FieldServe extends Model {

    /**
     * Notes:字段列表
     * User: ZhuHaili
     * Date: 菜单
     */
    function getFieldList($mouldCode, $sortFlag, $tableId = 1){
        $sortFlag = intval($sortFlag);
        $tableId = intval($tableId) ? intval($tableId) : 1;
        if(!$sortFlag){
            return array();
        }
        $fieldM = new Admin_FieldModel();
        $list = $fieldM->getFieldList($mouldCode, $sortFlag, $tableId);
        $statusArr = BaseData::$statusArr3;
        $typesArr = BaseData::$fieldTypeArr;
        foreach($list as $k=>$v){
            $list[$k]['statustxt'] = isset($statusArr[$v['status']]) ? $statusArr[$v['status']] : '';
            $list[$k]['fieldtypetxt'] = isset($typesArr[$v['fieldtype']]) ? $typesArr[$v['fieldtype']] : '';
        }
        return $list;
    }

    /**
     * Notes:字段添加
     * User: ZhuHaili
     */
    function addField($params){
        // 参数验证
        $data = $this->paramVerify($params);
        if(!is_array($data)){
            return $data;
        }
        $menu_idParam = $data['open_menu_id'];
        $classDescParam = $data['open_classdesc'];
        $classRuleParam = $data['open_classrule'];
        $fieldType = $data['table_field_type'];
        unset($data['open_menu_id']);
        unset($data['open_classdesc']);
        unset($data['open_classrule']);
        unset($data['table_field_type']);
        // 字段是否存在验证
        $existRes = $this->fieldVerify($data);
        if($existRes != 'Y'){
            return $existRes;
        }
        // 保存字段信息
        $db = $this->conn('mysql');
        $id = $db->addData('sysfield', $data, 'id');
        if(!$id){
            return '字段信息保存失败';
        }
        // 保存字段开放菜单关联信息
        foreach($menu_idParam as $k=>$v){
            $dataD['f_id'] = $id;
            $dataD['menu_id'] = $v;
            $dataD['fielddesc'] = isset($classDescParam[$k]) ? $classDescParam[$k] : '';
            $dataD['fieldclassrule'] = isset($classRuleParam[$k]) ? $classRuleParam[$k] : '';
            $result = $db->addData('sysfield_detail', $dataD);
            if(!$result){
                return '菜单ID为'.$v.' 关联信息添加失败！';
            }
        }
        // 向数据表中添加字段
        $table = '';
        if($data['sortflag'] == 1){
            $table = 'sysmenu';
        }else if($data['tableid'] == 1){
            $table = $data['mould_code'];
        }else if($data['tableid'] == 2){
            $table = $data['mould_code'].'_detail';
        }else if($data['tableid'] == 3){
            $table = $data['mould_code'].'_side';
        }
        if($table){
            $tableFieldAddRes = $this->tableAddField($table, $data['fieldcode'], $fieldType, $data['fieldval'], $data['fieldname']);
            if($tableFieldAddRes != 'Y'){
                return $tableFieldAddRes;
            }
        }
        return 'Y';
    }

    /**
     * Notes:字段详情
     * User: ZHL
     */
    function getFieldInfo($id){
        $id = intval($id);
        if(!$id){
            return array();
        }
        $fieldM = new Admin_FieldModel();
        $info = $fieldM->getFieldInfo($id);
        $info['detail'] = $fieldM->getFieldDetailInfo($id);
        return $info;
    }

    /**
     * Notes:字段修改
     * User: ZhuHaili
     */
    function updateField($params){
        $id = intval($params['id']);
        if(!$id){
            return '网络异常，刷新重试';
        }
        // 参数验证
        $data = $this->paramVerify($params);
        if(!is_array($data)){
            return $data;
        }
        $menu_idParam = $data['open_menu_id'];
        $classDescParam = $data['open_classdesc'];
        $classRuleParam = $data['open_classrule'];
        $fieldType = $data['table_field_type'];
        unset($data['open_menu_id']);
        unset($data['open_classdesc']);
        unset($data['open_classrule']);
        unset($data['table_field_type']);
        // 验证字段状态
        $fieldM = new Admin_FieldModel();
        $fieldInfo = $fieldM->getFieldInfo($id);
        if(empty($fieldInfo)){
            return '你要修改的字段异常请检查数据库';
        }
        if(!$fieldInfo['fieldcode']){
            return '你要修改的字段异常请检查数据库';
        }
        // 修改字段信息
        $where['id'] = $id;
        $db = $this->conn('mysql');
        $result = $db->updateData('sysfield', $data, $where);
        if(!$result){
            return '字段信息修改失败';
        }
        // 删除旧的字段关联信息
        $whereD['f_id'] = $id;
        $result = $db->delData('sysfield_detail',$whereD);
        /*if(!$result){
            return '更新字段关联失败';
        }*/
        // 保存字段开放菜单信息
        foreach($menu_idParam as $k=>$v){
            $dataD['f_id'] = $id;
            $dataD['menu_id'] = $v;
            $dataD['fielddesc'] = isset($classDescParam[$k]) ? $classDescParam[$k] : '';
            $dataD['fieldclassrule'] = isset($classRuleParam[$k]) ? $classRuleParam[$k] : '';
            $result = $db->addData('sysfield_detail', $dataD);
            if(!$result){
                return '菜单ID为'.$v.' 关联添加失败！';
            }
        }
        // 数据表中修改字段
        $table = '';
        if($data['sortflag'] == 1){
            $table = 'sysmenu';
        }else if($data['tableid'] == 1){
            $table = $data['mould_code'];
        }else if($data['tableid'] == 2){
            $table = $data['mould_code'].'_detail';
        }else if($data['tableid'] == 3){
            $table = $data['mould_code'].'_side';
        }
        if($table){
            $tableFieldARes = $this->tableUpdateField($table, $fieldInfo['fieldcode'], $data['fieldcode'], $fieldType, $data['fieldval'], $data['fieldname']);
            if($tableFieldARes != 'Y'){
                return $tableFieldARes;
            }
        }
        return 'Y';
    }

    /**
     * Notes:字段删除
     * User: ZhuHaili
     */
    function delField($id){
        // 判断参数
        $id = intval($id);
        if(!$id){
            return '网络异常，刷新重试';
        }
        // 判断字段信息状态
        $fieldM = new Admin_FieldModel();
        $fieldInfo = $fieldM->getFieldInfo($id);
        if(empty($fieldInfo)){
            return '没有找到字段无法删除';
        }
        // 删除主表记录
        $where['id'] = $id;
        $db = $this->conn('mysql');
        $result = $db->delData('sysfield', $where);
        if(!$result){
            return '删除失败';
        }
        // 删除字段关联信息记录
        $whereD['f_id'] = $id;
        $db->delData('sysfield_detail', $whereD);
        // 验证字段是否存在数据结构表中
        $verifyRes = $this->fieldVerify($fieldInfo);
        if($verifyRes == 'Y'){
            return 'Y'; // 字段已经不存在了，直接返回删除成功
        }
        // 字段存在数据表结构中时进行删除字段操作
        $table = $fieldInfo['sortflag'] == 1 ? 'sysmenu' : ($fieldInfo['tableid'] == 1 ? $fieldInfo['mould_code'] : $fieldInfo['mould_code'].'_detail');
        $tableRes = $this->tableDelField($table, $fieldInfo['fieldcode']);
        if($tableRes != 'Y'){
            return $tableRes;
        }
        return 'Y';
    }

    /**
     * Notes:排序
     * User: ZhuHaili
     */
    function seqOrderBy($param){
        if(!is_array($param)){
            return '排序失败';
        }
        foreach($param as $id=>$seq){
            $where['id'] = $id;
            $data['viewseq'] = intval($seq);
            $this->conn('mysql')->updateData('sysfield', $data, $where);
        }
        return 'Y';
    }

    /**
     * Notes: 参数初始化验证
     * User: ZhuHaili
     * Date: 菜单
     */
    private function paramVerify($params){
        $data = array();
        // 验证必填参数
        $mustParam = array(
            'mould_code'=>'模型编码', 'fieldname'=>'字段名称', 'fieldcode'=>'字段标识', 'fieldtype'=>'字段类型', 'banflag'=>'禁用标识',
        );
        foreach($mustParam as $k=>$v){
            if(!isset($params[$k]) || !$params[$k]){
                return $k.'不能为空';
            }else{
                $data[$k] = $params[$k];
            }
        }
        // 字符串参数值初始化
        $defaultParam = array('fieldval'=>null, 'fieldrule'=>null, 'fieldrule2'=>null, 'fieldhint'=>null);
        foreach($defaultParam as $k=>$v){
            $data[$k] = isset($params[$k]) && ($params[$k] || $params[$k] == 0) ? $params[$k] : $v;
        }

        // 整型参数值初始化
        $intParam = array(
            'fieldlong'=>200,'showwidth'=>280, 'showheight'=>30, 'showflag'=>1,
            'sortflag'=>1, 'tableid'=>1, 'status'=>1, 'viewseq'=>0, 'tdwidth'=>0, 'banflag'=>2,'cutflag'=>0,'cuttype'=>0,
        );
        foreach($intParam as $k=>$v){
            $data[$k] = isset($params[$k]) ? (intval($params[$k]) ? intval($params[$k]) : $v) : $v;
        }

        // 字段类型和长度初始化
        $data['table_field_type'] = 'varchar('.$data['fieldlong'].')';
        if($params['fieldtype'] == 2){ // 富文本
            $data['fieldlong'] = '';
            $data['table_field_type'] = 'text';
        }
        if($params['fieldtype'] == 3){ // 整数
            $data['fieldval'] = 0;
            $data['fieldlong'] = 10;
            $data['table_field_type'] = 'int(10)';
        }
        if($params['fieldtype'] == 4){ // 货币
            $data['fieldval'] = 0;
            $data['fieldlong'] = 9;
            $data['table_field_type'] = 'decimal(9,2)';
        }
        if(in_array($params['fieldtype'], array(14, 16))){ // 多图片多文件
            $data['fieldlong'] = 500;
            $data['table_field_type'] = 'varchar(500)';
        }
        $data['createdate'] = date('Y-m-d H:i:s');
        // 开放菜单参数初始化
        $data['open_menu_id'] = isset($params['open_menu_id']) ? $params['open_menu_id'] : array();
        $data['open_classdesc'] = isset($params['open_classdesc']) ? $params['open_classdesc'] : array();
        $data['open_classrule'] = isset($params['open_classrule']) ? $params['open_classrule'] : array();
        return $data;
    }

    /**
     * Notes:字段验证-判断字段否已经存在表中
     * User: ZhuHaili
     * Date: 菜单
     */
    private function getTableField($table, $field){
        if(!$table || !$field){
            return false;
        }
        $fieldM = new Admin_FieldModel();
        $res = $fieldM->getTableField($table, $field);
        return isset($res[0]['counts']) && $res[0]['counts'] ? true : false;
    }

    /**
     * Notes: 字段验证-判断菜单表、主表、副表是否已经存在该字段
     * User: ZhuHaili
     */
    private function fieldVerify($params){
        // 为菜单字段时，判断是否已经在表中
        if($params['sortflag'] == 1){
            $res = $this->getTableField('sysmenu', $params['fieldcode']);
            if($res){
                return '当前字段已经存在请更换字段标识';
            }
        }
        // 为模型表字段时，判断是否已经在表中
        if($params['sortflag'] == 2){
            // 判断主表
            $res = $this->getTableField($params['mould_code'], $params['fieldcode']);
            if($res){
                return '当前字段已经存在请更换字段标识';
            }
            // 判断副表
            $res = $this->getTableField($params['mould_code'].'_detail', $params['fieldcode']);
            if($res){
                return '当前字段已经存在请更换字段标识';
            }
        }
        return 'Y';
    }

    /**
     * Notes:数据表中添加字段
     * User: ZhuHaili
     */
    private function tableAddField($table, $field, $fieldType, $defaultVal, $fieldDesc){
        $db = $this->conn('mysql');
        $table = $db->db_fix . $table;
        $defaultVal = $defaultVal ? $defaultVal : 'null';
        $sql = "alter table `$table` add column `$field` $fieldType default $defaultVal comment '$fieldDesc'";
        $result = $db->query($sql);
        if(!$result){
            return '数据表字段插入失败';
        }
        return 'Y';
    }

    /**
     * Notes:数据表中修改字段
     * User: ZhuHaili
     */
    private function tableUpdateField($table, $oldField, $field, $fieldType, $defaultVal, $fieldDesc){
        $db = $this->conn('mysql');
        $table = $db->db_fix . $table;
        $defaultVal = $defaultVal ? $defaultVal : 'null';
        $sql = "alter  table `$table` change $oldField $field $fieldType default $defaultVal comment '$fieldDesc'";
        $result = $db->query($sql);
        if(!$result){
            return '数据表字段修改失败';
        }
        return 'Y';
    }

    /**
     * Notes:数据表中删除字段
     * User: ZhuHaili
     */
    private function tableDelField($table, $field){
        $db = $this->conn('mysql');
        $table = $db->db_fix . $table;
        $sql = "alter table `$table` drop column $field";
        $result = $db->query($sql);
        if(!$result){
            return '数据表字段删除失败';
        }
        return 'Y';
    }

    /**
     * Notes:获取菜单下开放的字段
     * User: ZHL
     */
    function getOpenClassFieldsInfos($menu_id, $sortFlag, $tableId){
        if(!$menu_id || !$sortFlag || !$tableId){
            return array();
        }
        $fieldM = new Admin_FieldModel();
        return $fieldM->getOpenClassFieldsInfos($menu_id, $sortFlag, $tableId);
    }
}